<!-- 虚拟钥匙控车单 -->
<template>
  <div class="page-container">
    <page-form :model="form" :rules="rules" layout="vertical" div="true" ref="formRef">
      <card class="add-info-card" title="虚拟钥匙控车单" toggle :showDivider="false">
        <page-form-row>
          <page-form-item field="carId" label="车牌号">
            <!-- 查绑定tbox的车辆信息 -->
            <remote-select
              :disabled="pageType == 'edit'"
              :params="{ bindTboxVehicle: 1 }"
              v-model="form.carId"
              :allow-clear="false"
              type="car_licenseno_list"
              @change="changeCarFn"
            />
          </page-form-item>
          <page-form-item label="车架号">
            <i-input placeholder="--" disabled v-model="carInfo.vin" />
          </page-form-item>
          <page-form-item label="车型">
            <i-input placeholder="--" disabled v-model="carInfo.modelName" />
          </page-form-item>
          <page-form-item label="车牌颜色">
            <i-input placeholder="--" disabled v-model="carInfo.licenseNoColorName" />
          </page-form-item>
          <page-form-item label="设备SN/ID">
            <i-input placeholder="--" disabled v-model="carInfo.tboxVehicleSn" />
          </page-form-item>
          <page-form-item label="设备供应商">
            <i-input placeholder="--" disabled v-model="carInfo.tboxVehicleFirm" />
          </page-form-item>
        </page-form-row>
      </card>
      <card class="add-info-card" title="详情" toggle :showDivider="false">
        <page-form-row>
          <page-form-item field="startTime" label="开始时间">
            <i-date-picker
              :disabled="![0, 1].includes(form.status) && pageType == 'edit'"
              popup-container=".virtual-date"
              class="w-full"
              position="bl"
              :disabled-date="(date) => disabledDateFn(date, 'start')"
              :disabledTime="disabledStartTime"
              v-model="form.startTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
            />
          </page-form-item>
          <page-form-item field="endTime" label="结束时间">
            <i-date-picker
              popup-container=".virtual-date"
              :disabled="![0, 1, 2, 3].includes(form.status) && pageType == 'edit'"
              class="w-full"
              position="bl"
              :disabled-date="(date) => disabledDateFn(date, 'end')"
              :disabledTime="disabledEndTime"
              v-model="form.endTime"
              show-time
              format="YYYY-MM-DD HH:mm:ss"
            />
          </page-form-item>
          <page-form-item field="refType" label="关联业务类型">
            <a-select v-model="form.refType" placeholder="请选择" :disabled="pageType == 'edit'">
              <a-option v-for="item in carVirtualDict.refTypeEnums" :key="item.value" :value="item.value" :label="item.label" />
            </a-select>
          </page-form-item>
          <page-form-item field="memberName" label="控车人姓名">
            <i-input placeholder="请输入" v-model.trim="form.memberName" max-length="50" />
          </page-form-item>
          <page-form-item field="memberPhone" label="控车人电话">
            <i-input placeholder="请输入" :disabled="pageType == 'edit'" v-model.trim="form.memberPhone" max-length="11" />
          </page-form-item>
          <page-form-item field="refCode" label="关联业务单号">
            <i-input placeholder="请输入" v-model.trim="form.refCode" :disabled="pageType == 'edit'" max-length="50" />
          </page-form-item>
        </page-form-row>
      </card>
      <card class="add-info-card" title="其他信息" toggle :showDivider="false">
        <page-form-row>
          <page-form-item field="remark" label="备注" :span="24">
            <a-textarea class="textarea-in" placeholder="请输入" :max-length="200" v-model.trim="form.remark" auto-size />
          </page-form-item>
        </page-form-row>
      </card>
    </page-form>
  </div>
  <page-form-footer @ok="submitFn" :ok-loading="okLoading" />
</template>

<script setup name="CarVirtualKeyForm">
  import useNavigate from '@/hooks/useNavigate'
  import { onMounted, ref } from 'vue'
  import { carControlDetail, carControlCreate, carControlModify } from '@/api/asset/virtualKey'
  import dayjs from 'dayjs'
  import { Message } from '@arco-design/web-vue'

  import { useRoute } from 'vue-router'
  const { navigateBack } = useNavigate()
  const route = useRoute()
  const routePrams = route.params

  import { usePageDict } from '@/hooks/useDict'
  const carVirtualDict = usePageDict('carVirtualDict')

  const form = ref({
    startTime: '',
    endTime: '',
  })

  // 表单规则
  const rules = {
    carId: [{ required: true, message: '请选择车牌号', trigger: 'change' }],
    memberPhone: [
      { required: true, message: '请输入控车人电话', trigger: 'blur' },
      { match: /^1\d{10}$/, message: '请输入正确的手机号', trigger: 'blur' },
    ],
    startTime: [{ required: true, message: '请选择开始时间', trigger: 'change' }],
    endTime: [{ required: true, message: '请选择结束时间', trigger: 'change' }],
    refCode: [{ required: false, message: '只允许输入数字和字母', trigger: 'blur', match: /^[a-zA-Z0-9]+$/ }],
  }

  const disabledDateFn = (date, type) => {
    if (type == 'start') {
      return dayjs(date).isBefore(dayjs().subtract(1, 'day')) || dayjs(date).isAfter(dayjs().add(1, 'month'))
    } else {
      return dayjs(date).isBefore(dayjs().subtract(1, 'day')) || dayjs(date).isAfter(dayjs().add(1, 'day').add(1, 'month'))
    }
  }
  const generateRange = (start, end) => {
    const result = []
    for (let i = start; i < end; i++) {
      result.push(i)
    }
    return result
  }
  const disabledStartTime = (date) => {
    // 获取当前时间
    const now = dayjs()

    // 如果选择的日期是今天，禁用当前时间之前的时间
    if (dayjs(date).isSame(now, 'day')) {
      const currentHour = now.hour()
      const currentMinute = now.minute()
      const currentSecond = now.second()

      return {
        disabledHours: () => generateRange(0, currentHour),
        disabledMinutes: (hour) => (hour === currentHour ? generateRange(0, currentMinute) : []),
        disabledSeconds: (hour, minute) => (hour === currentHour && minute === currentMinute ? generateRange(0, currentSecond) : []),
      }
    }

    // 对于非今天的日期，不限制时间
    return {
      disabledHours: () => [],
      disabledMinutes: () => [],
      disabledSeconds: () => [],
    }
  }
  const disabledEndTime = (date) => {
    const now = dayjs()
    const oneMonthLater = now.add(1, 'month').add(1, 'day')

    // 如果选择的日期是一个月后的日期，禁用所有时间
    if (dayjs(date).isSame(oneMonthLater, 'day')) {
      const monthLaterHour = oneMonthLater.hour()
      const monthLaterMinute = oneMonthLater.minute()
      const monthLaterSecond = oneMonthLater.second()

      return {
        disabledHours: () => generateRange(monthLaterHour + 1, 24),
        disabledMinutes: (hour) => (hour === monthLaterHour ? generateRange(monthLaterMinute + 1, 60) : []),
        disabledSeconds: (hour, minute) =>
          hour === monthLaterHour && minute === monthLaterMinute ? generateRange(monthLaterSecond + 1, 60) : [],
      }
    }

    // 对于不是一个月后那一天的日期，不限制时间
    return {
      disabledHours: () => [],
      disabledMinutes: () => [],
      disabledSeconds: () => [],
    }
  }

  const carInfo = ref({})
  const changeCarFn = (_, option = {}) => {
    option.carId = option.id
    carInfo.value = option
  }

  const getDates = () => {
    form.value.startTime = dayjs(getNowDate(0)).format('YYYY-MM-DD HH:mm:ss')
    form.value.endTime = dayjs(getNowDate(0)).add(1, 'day').format('YYYY-MM-DD HH:mm:ss')
  }

  // 编辑获取详情
  const getDetail = (id) => {
    carControlDetail({ id: id }).then((res) => {
      let { result } = res
      form.value = result
      carInfo.value = {
        vin: result.vin,
        modelName: result.modelName,
        licenseNoColorName: result.licenseColor,
        tboxVehicleSn: result.equipmentId,
        tboxVehicleFirm: result.supplier,
      }
    })
  }

  // 默认日期时间
  const getNowDate = (n) => {
    let timestamp = Date.parse(new Date())
    timestamp = timestamp / 1000
    timestamp += Number(n) * 86400
    return new Date(timestamp * 1000)
  }

  const formRef = ref()
  const okLoading = ref(false)
  const submitFn = (noticeSuccess) => {
    formRef.value.validate((error) => {
      if (!error) {
        okLoading.value = true
        let { startTime, endTime } = form.value
        // 开始时间不大于结束时间
        if (dayjs(startTime).unix() >= dayjs(endTime).unix()) {
          okLoading.value = false
          return Message.warning('开始时间不能大于结束时间')
        }
        // 结束时间不能小于开始时间1小时
        if (dayjs(endTime).unix() - dayjs(startTime).unix() < 3600) {
          okLoading.value = false
          return Message.warning('结束时间不能小于开始时间1小时')
        }
        if (pageType.value == 'create') {
          // 新增的时候，开始时间不大于当前时间
          // if (dayjs(startTime).unix() < dayjs(getNowDate(0)).unix()) {
          //   okLoading.value = false
          //   return Message.warning('开始时间不能小于当前时间')
          // }
          carControlCreate({ ...form.value })
            .then(() => {
              noticeSuccess()
              navigateBack()
            })
            .finally(() => {
              okLoading.value = false
            })
        } else {
          carControlModify({ ...form.value })
            .then(() => {
              noticeSuccess()
              navigateBack()
            })
            .finally(() => {
              okLoading.value = false
            })
        }
      }
    })
  }
  const pageType = ref('')
  onMounted(() => {
    const id = routePrams.id
    if (id) {
      getDetail(id)
      pageType.value = 'edit'
    } else {
      getDates()
      pageType.value = 'create'
    }
  })
</script>

<style lang="less" scoped>
  .textarea-in {
    width: 100%;
    height: 100px;
  }
  .virtual-date {
    width: 100%;
    max-height: 70vh;
    position: relative;
  }
</style>
